package com.example.demo.error;

import com.example.demo.code.CustomStatusCode;
import com.example.demo.exceptions.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import javax.management.InstanceNotFoundException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理记录已存在异常
     * 当尝试添加已存在的记录时，抛出此异常
     */
    @ExceptionHandler(RecordExistsException.class)
    public ResponseEntity<ApiResponse> handleRecordExistsException(RecordExistsException ex) {
        return ResponseEntity.ok(new ApiResponse(CustomStatusCode.DUPLICATE_RESOURCE, null, 0));
    }

    /**
     * 处理记录未找到异常
     * 当尝试访问不存在的记录时，抛出此异常
     */
    @ExceptionHandler(RecordNotFoundException.class)
    public ResponseEntity<ApiResponse> handleRecordNotFoundException(RecordNotFoundException ex) {
        return ResponseEntity.ok(new ApiResponse(CustomStatusCode.RESOURCE_NOT_FOUND, ex.getMessage(), 0));
    }

    /**
     * 处理记录不可删除异常
     * 当尝试删除不可删除的记录时，抛出此异常
     */
    @ExceptionHandler(RecordNotDeletableException.class)
    public ResponseEntity<ApiResponse> handleRecordNotDeletableException(RecordNotDeletableException ex) {
        return ResponseEntity.ok(new ApiResponse(CustomStatusCode.ACCESS_DENIED, null, 0));
    }

    /**
     * 处理数据库操作异常
     * 当数据库操作失败时，抛出此异常
     */
    @ExceptionHandler(DatabaseOperationException.class)
    public ResponseEntity<ApiResponse> handleDatabaseOperationException(DatabaseOperationException ex) {
        return ResponseEntity.ok(new ApiResponse(CustomStatusCode.DATABASE_ERROR, null, 0));
    }

    /**
     * 处理其他异常
     * 处理未处理的异常，返回错误码
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse> handleException(Exception ex) {
        // 记录异常信息
        ex.printStackTrace(); // 或者使用slf4j等日志框架记录
        return ResponseEntity.ok(new ApiResponse(CustomStatusCode.INTERNAL_ERROR,null, 0));
    }

    /**
     * 处理权限不足异常
     * 当尝试访问没有权限的资源时，抛出此异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<ApiResponse> handleAccessDeniedException(AccessDeniedException ex) {
        return ResponseEntity.ok(new ApiResponse(CustomStatusCode.ACCESS_DENIED, null, 0));
    }




}